package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.Permission;
import cn.wolfcode.exception.BusinessException;
import cn.wolfcode.mapper.EmployeeMapper;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IEmployeeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@Service
@Transactional
public class EmployeeServiceImpl implements IEmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;
    @Override
    public void insert(Employee employee, Long[] roleIds) {
        employeeMapper.insert(employee);
        if(roleIds != null){
            for (Long roleId : roleIds) {
                employeeMapper.insertRelevance(employee.getId(), roleId);
            }
        }
    }

    @Override
    public void delete(Long id) {
        employeeMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void update(Employee employee, Long[] roleIds) {
        employeeMapper.updateByPrimaryKey(employee);
        employeeMapper.deleteRelevance(employee.getId());
        if(roleIds != null){
            for (Long roleId : roleIds) {
                employeeMapper.insertRelevance(employee.getId(), roleId);
            }
        }
    }

    @Override
    public Employee get(Long id) {
        return employeeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Employee> selectAll() {
        return employeeMapper.selectAll();
    }

    @Override
    public PageInfo<Employee> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        List<Employee> list = employeeMapper.queryList(qo);
        return new PageInfo<>(list);
    }

    @Override
    public Employee checkEmp(String username, String password) {
        if(StringUtils.isEmpty(username)){
            throw new BusinessException("用户名不能为空");
        }
        if(StringUtils.isEmpty(password)){
            throw new BusinessException("密码不能为空");
        }
        Employee employee = employeeMapper.checkEmp(username);
        if(employee == null){
            throw new BusinessException("用户不存在");
        }
        if(!password.equals(employee.getPassword())){
            throw new BusinessException("密码错误");
        }
        return employee;
    }

    @Override
    public List<Permission> selectPermissions(Long employeeId) {
        return employeeMapper.selectPermissions(employeeId);
    }

    /**
     * 实现文件导出功能
     * @return 返回Excel文件对象
     */
    @Override
    public Workbook exportXls() {
        //创建文件对象并设置第一行表头
        Workbook wb = new HSSFWorkbook();
        Sheet sheet = wb.createSheet("员工信息表");
        Row row = sheet.createRow(0);
        row.createCell(0).setCellValue("用户名");
        row.createCell(1).setCellValue("姓名");
        row.createCell(2).setCellValue("邮箱");
        row.createCell(3).setCellValue("年龄");
        row.createCell(4).setCellValue("部门");

        List<Employee> employees = employeeMapper.selectAll();
        //遍历员工信息存入文件对象中
        for (int i = 0; i < employees.size(); i++) {
            row = sheet.createRow(i + 1);
            Employee employee = employees.get(i);
            row.createCell(0).setCellValue(employee.getUsername());
            row.createCell(1).setCellValue(employee.getName());
            row.createCell(2).setCellValue(employee.getEmail());
            row.createCell(3).setCellValue(employee.getAge());
            if(employee.getDept() != null){
                row.createCell(4).setCellValue(employee.getDept().getName());
            }
        }
        return wb;
    }

    /**
     * 实现文件导入功能
     * @param file 用户导入的文件
     */
    @Override
    public void importXls(MultipartFile file) {
        try {
            //创建excel文件对象
            Workbook wb = WorkbookFactory.create(file.getInputStream());
            //获取第一页
            Sheet sheet = wb.getSheetAt(0);
            //获取最后一行的索引
            int lastRowNum = sheet.getLastRowNum();
            for (int i = 1; i <= lastRowNum; i++) {
                //获取第2行(第一行为表头不需要)
                Row row = sheet.getRow(i);
                String username = row.getCell(0).getStringCellValue();
                if(username == null){
                    return;
                }
                Employee employee = new Employee();
                employee.setUsername(username);
                employee.setName(row.getCell(1).getStringCellValue());

                //判断年龄的格式
                CellType cellType = row.getCell(2).getCellType();
                if(cellType == CellType.NUMERIC){
                    employee.setAge((int)row.getCell(2).getNumericCellValue());
                }else{
                    employee.setAge(Integer.valueOf(row.getCell(2).getStringCellValue()));
                }
                employee.setEmail(row.getCell(3).getStringCellValue());
                employeeMapper.insert(employee);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
